package com.xsqf.jt808.netty.handler;


import com.xsqf.jt808.common.vo.req.terminal.LogOutMsg;
import com.xsqf.jt808.common.vo.resp.CommonResp;
import com.xsqf.jt808.entity.VehicleRegisterInfo;
import com.xsqf.jt808.service.IVehicleRegisterInfoService;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


/**
 * @Author:
 * @Date: 2020-5-14
 * @Description: 注销消息->CommonResp
 * @Version: 1.0
 */

@Slf4j
@Component
@ChannelHandler.Sharable
public class LogOutMsgHandler extends BaseHandler<LogOutMsg> {

//    @Autowired
//    RegisterInfoDao registerInfoDao;
    @Autowired
IVehicleRegisterInfoService registerInfoService;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, LogOutMsg msg) throws Exception {
        log.info("注销：" + msg.toString());
        CommonResp resp = logOut(msg, getSerialNumber(ctx.channel()));
        write(ctx, resp);
    }


    public CommonResp logOut(LogOutMsg msg, short flowId) {
        CommonResp resp = new CommonResp();
        resp.getHeader().setTerminalPhone(msg.getHeader().getTerminalPhone());
        resp.getHeader().setFlowId(flowId);
        resp.setReplyFlowId(msg.getHeader().getFlowId());
        resp.setReplyId(msg.getHeader().getMsgId());
        resp.setResult(CommonResp.FAILURE);

        //验证session信息
        Object isAuthenticated = redisTemplate.opsForHash()
                .get("KEY:" + msg.getHeader().getTerminalPhone(), "isAuthenticated");
        if (isAuthenticated != null) {

            //删除车辆注册信息
            VehicleRegisterInfo registerInfo = registerInfoService.findByTerminalId(msg.getHeader().getTerminalPhone());
            if (registerInfo != null) {
                registerInfo.setDeleted("1");
                try {
                    registerInfoService.save(registerInfo);
                    resp.setResult(CommonResp.SUCCESS);
                    redisTemplate.opsForHash().delete("KEY:" + msg.getHeader().getTerminalPhone(), "isAuthenticated");

                } catch (Exception e) {
                    return resp;
                }
            }
        }

        return resp;
    }
}
